/**
 * @author  zhanshi Liu
 * @date    2020/03/22
 * @website www.jhmsona.cn
 */
Vue.component('treeselect', VueTreeselect.Treeselect)
let vm = new Vue({
    el:'#vm',
    data:{
        dictList:undefined,
        tableData:[],
        currentPage:1,
        count:0,
        title:undefined,
        dict:undefined,
        options:[],
        roleOptions:[],
        postOptions:[],
        genderOptions:[],
        statusOptions:[],
        dialogFormVisible: false,
        formLabelWidth: '80px',
        dictType: 'sys_user_gender',
        dictTypeStatus:'sys_status',
        respForm:{},
        userIds:null,
        form:{
            username:undefined,
            status:undefined,
            page:1,
            limit:10,
        },
        rules: {
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
            //,password: [{ required: true, message: '请输密码', trigger: 'blur' }]
            ,mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
                { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,message: "请输入正确的手机号",trigger: "blur"}]
            ,email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: "email", message: "请输入正确的邮箱地址",trigger: ["blur", "change"]}]
            ,deptId: [{required: true, message: '请选择一个部门', trigger: ['change'] }]
        }
    },
    created:function (){
        this.getDictList();
    },
    mounted:function(){
        this.getStatus();
    },
    methods:{
        getDictList(){
            axios.get('/sys/dict/getDictList').then((res)=> {
                this.dictList = res.data;
                axios.get('/sys/user/getUserByWhere', {
                    params: {
                        data:JSON.stringify(this.form)
                    }
                }).then(res => {
                    res.data.data.forEach(item => {
                        for( let key in this.dictList){
                            if (this.dictType+"_"+item.gender==key){
                                item.gender= this.dictList[key];
                            }else if (this.dictTypeStatus+"_"+item.status == key){
                                item.status=this.dictList[key];
                            }
                        }
                    })
                    this.tableData=res.data.data;
                    this.count = res.data.count;
                }).catch(res=> {
                    console.log(res);
                });
            });
        },
        getDepart(){
            axios.get('/sys/dept/selectList')
            .then((res)=> {
                let item = res.data.data;
                this.screenData(item);
                this.options=item;
            })
        },
        getGender(){
            axios.get('/sys/dict/getDictByType',{
                params:{
                    dictType:this.dictType
                }
            }).then(res=> {
                this.genderOptions = res.data.data;
            })
        },
        getStatus(){
            axios.get('/sys/dict/getDictByType',{
                params:{
                    dictType:this.dictTypeStatus
                }
            }).then(res=> {
                this.statusOptions = res.data.data;
            })
        },
        screenData(item){//剔除children为空的数组
            item.forEach(item =>{
                item.children.length===0  ? delete item.children : this.screenData(item.children)
            })
        },
        resetForm(){
            this.respForm={
                userId: undefined,
                deptId: undefined,
                username: undefined,
                password: undefined,
                mobile: undefined,
                email: undefined,
                gender: undefined,
                status: '0',
                remark: undefined,
                postIds: [],
                roleIds: []
            }
        },
        edit(index,row){//编辑
            this.dialogFormVisible = true;
            this.resetForm();
            this.title="编辑用户";
            this.getDepart();
            this.getGender();
            axios.get('/sys/user/getUserByUserId',{
                params:{
                    userId:row.userId
                }
            }).then(res=> {
                this.respForm = res.data.data;
                this.respForm.roleIds = res.data.roleIds;//已有角色Ids
                this.respForm.postIds = res.data.postIds;//已有岗位Ids
                this.roleOptions = res.data.role;//所有角色
                this.postOptions = res.data.post;//所有岗位
            })
        },
        selectionChange(val){//多选
            this.userIds = val.map(item => item.userId);
        },
        search(){
            this.getDictList();
        },
        reset(form1){
            this.$refs[form1].resetFields()
        },
        handleSizeChange(val) {
            this.form.limit = val;
            this.getDictList();
        },
        handleCurrentChange(val) {
            this.form.page = val;
            this.getDictList();
        },
        statusChange(){
            this.getDictList();
        },
        add(){//添加
            this.resetForm();
            this.dialogFormVisible = true;
            this.title="添加用户";
            this.getDepart();
            this.getGender();
            axios.get('/sys/user/getUserByUserId').then(res=> {
                this.roleOptions = res.data.role;//所有角色
                this.postOptions = res.data.post;//所有岗位
            })
        },
        remove(row){
            let ids = row.userId || this.userIds;//等价与if(row.userId!=null ||row.userId!=""){let ids = row.userId}else if......
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.ajax({
                    url:'/sys/user/del',
                    dataType:'json',
                    traditional:true,
                    type:'delete',
                    data:{
                        ids:ids
                    },
                    success:res=>{
                        if (res.code===200){
                            this.$notify({title:'成功',message:res.msg,type:'success'});
                            this.getDictList();
                        } else{
                            this.$notify({title:'警告',message:res.msg,type:'warning'});
                        }
                    }
                })
            }).catch(() => {
                this.$notify({type: 'info', message: '已取消删除',title:"提示"});
            });

        },
        exportData(){
            this.$confirm('此操作将导出选中数据、未选择导出所有数据, 是否继续?', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if(this.userIds!=null && this.userIds!=undefined){
                    axios.get('/sys/user/export',{
                        params:{ userIds:encodeURI(this.userIds)},
                        responseType:'blob'
                    }).then(res=> {
                        this.downloadExport(res);
                    })
                }else{
                    axios.get('/sys/user/export',{
                        responseType:'blob'
                    }).then(res=> {
                        this.downloadExport(res);
                    })
                }
            }).catch(() => {
                this.$notify({type: 'info', message: '导出已取消',title:"提示"});
            });
        },
        submitForm(val){//提交
            this.$refs[val].validate(valid => {
                if(valid){
                    if(this.respForm.userId === undefined){
                        axios.post('/sys/user/addSysUser', this.respForm)
                            .then(res => {
                                if(res.data.code===200){
                                    this.$notify({ title: '成功',message: res.data.msg,type: 'success' });
                                    this.dialogFormVisible = false;
                                    this.getDictList();
                                }else{
                                    this.$notify({title: '警告',message:res.data.msg,type: 'warning'});
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                this.$notify({title: '警告',message:JSON.parse(error.responseText).message,type: 'warning'});
                            })
                    }else{
                       $.ajax({
                           url:'/sys/user/modify',
                           dataType: 'json',
                           type:'put',
                           data:{
                               data:JSON.stringify(this.respForm)
                           },
                           success:res=>{
                               if(res.code===200){
                                   this.$notify({ title: '成功',message: res.msg,type: 'success' });
                                   this.dialogFormVisible = false;
                                   this.getDictList();
                               }else{
                                   this.$notify({title: '警告',message:res.msg,type: 'warning'});
                               }
                           }
                       })
                    }
                }
            });
        },
        downloadExport(res){
            const blob = new Blob([res.data]);
            const fileName = res.headers['filename'];
            if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
            } else { // IE下载
                navigator.msSaveBlob(blob, fileName);
            }
            if (res.status===200){
                this.$notify({ title: '成功',message: "导出成功",type: 'success' });
            }else{
                this.$notify({ title: '警告',message: "导出失败",type: 'warning' });
            }
        }
    }
})

